package com.addzero.web.infra.zip

import cn.hutool.core.collection.CollUtil
import cn.hutool.core.io.FileUtil
import cn.hutool.core.io.IoUtil
import cn.hutool.core.util.IdUtil
import cn.hutool.core.util.ZipUtil
import java.io.*
import java.nio.charset.Charset
import java.util.function.BiFunction
import java.util.function.Consumer
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

object JlZipUtil {


    fun saveFilesToDirectory(files: List<File>, directory: File) {
        if (CollUtil.isEmpty(files)) {
            return
        }
        for (file in files) {
            val newFile = File(directory, file.name)
            FileUtil.copy(file, newFile, true) // 使用Hutool的文件复制方法
        }
    }

    private fun createZipFile(files: Array<File> ): File {
        val zipFile = File.createTempFile("output", ".zip")
        val fileOutputStream = FileOutputStream(zipFile)
        val zipOutputStream = ZipOutputStream(fileOutputStream)
        files.forEach { addToZipFile(it, zipOutputStream) }
        return zipFile
    }

    private fun addToZipFile(dir: File, zipOut: ZipOutputStream) {
        val files = dir.listFiles()
        if (files != null) {
            for (file in files) {
                FileInputStream(file).use { fis ->
                    val zipEntry = ZipEntry(dir.name + "/" + file.name)
                    zipOut.putNextEntry(zipEntry)
                    val bytes = ByteArray(1024)
                    var length: Int
                    while ((fis.read(bytes).also { length = it }) >= 0) {
                        zipOut.write(bytes, 0, length)
                    }
                }
            }
        }
    }
}
